﻿using eDoctor.SDK.WeChat;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using zqdn.Web.Helpers;
namespace zqdn.Web.Controllers
{
    public class WxSdkController : Controller
    {
        /// <summary>
        /// 获取微信公众号的JS-SDK配置
        /// </summary>
        /// <param name="url"></param>
        /// <param name="debug"></param>
        JavaScriptSerializer Jss = new JavaScriptSerializer();
        //string host = "http://zqdn-dev.rndcn.com";
        string host = "http://zqdn.aegis-s.com";
        //吾测测微信配置
        //string Appid = "wxa3fe386216434a6b";
        //string Appsecret = "489858ba90a6b1bb6f2895ae0eb256a2";
        //最强大脑微信配置
        string Appid = "wx27a54ca734af2cf8";
        string Appsecret = "51501b489632695f29c7f2577c0ab9fe";
        public JavaScriptResult jsconfig(string url, bool debug)
        {
            var temp = @"wx.config({
                            debug: [_debug_], // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                            appId: '[_appId_]', // 必填，公众号的唯一标识
                            timestamp: [_timestamp_], // 必填，生成签名的时间戳
                            nonceStr: '[_nonceStr_]', // 必填，生成签名的随机串
                            signature: '[_signature_]',// 必填，签名，见附录1
                            jsApiList: [
                                'checkJsApi',
                                'onMenuShareTimeline',
                                'onMenuShareAppMessage',
                                'onMenuShareQQ',
                                'onMenuShareWeibo',
                                'hideMenuItems',
                                'showMenuItems',
                                'hideAllNonBaseMenuItem',
                                'showAllNonBaseMenuItem',
                                'translateVoice',
                                'startRecord',
                                'stopRecord',
                                'onRecordEnd',
                                'playVoice',
                                'pauseVoice',
                                'stopVoice',
                                'uploadVoice',
                                'downloadVoice',
                                'chooseImage',
                                'previewImage',
                                'uploadImage',
                                'downloadImage',
                                'getNetworkType',
                                'openLocation',
                                'getLocation',
                                'hideOptionMenu',
                                'showOptionMenu',
                                'closeWindow',
                                'scanQRCode',
                                'chooseWXPay',
                                'openProductSpecificView',
                                'addCard',
                                'chooseCard',
                                'openCard'
                            ] 
                        });";

            string jsapi_ticket, noncestr, signature;
            long timestamp;

            //var site = new WX_Site();

            ////获取微信公众号配置
            //site.GetAppConfig(out appid, out appsecret);

            //获取微信临时票据
            //jsapi_ticket = site.GetTicket();
            string acctoken = new WxController().GetAccessToken(Appid, Appsecret);
            string ReText = WebRequestPostOrGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + acctoken + "&type=jsapi", "");//post/get方法获取信息 
            Dictionary<string, object> DicText = (Dictionary<string, object>)Jss.DeserializeObject(ReText);
            jsapi_ticket = DicText["ticket"].ToString();
            //根据数据，生成签名


            signature = Call.Signature(jsapi_ticket, url, out noncestr, out timestamp);

            //替换模版中的参数
            temp = temp.Replace("[_debug_]", debug.ToString().ToLower()).Replace("[_appId_]", Appid).Replace("[_timestamp_]", timestamp.ToString()).Replace("[_nonceStr_]", noncestr).Replace("[_signature_]", signature);

            return JavaScript(temp);
        }
        /// <summary>
        /// 从腾讯下载图片
        /// </summary>
        /// <param name="media_ids"></param>
        /// <returns></returns>
        /// 
        [HttpPost]
        public ActionResult WechatDownLoadImg(List<string> serverIds, string urlWhere, string filetype)
        {
            Logs.Execute("serverIds.count:" + serverIds.Count);
            string acctoken = new WxController().GetAccessToken(Appid, Appsecret);
            if (string.IsNullOrWhiteSpace(urlWhere))
            {
                urlWhere = "img";
            }
            if (string.IsNullOrWhiteSpace(filetype))
            {
                filetype = ".jpg";
            }
            List<string> imgUrls = new List<string>();

            if (serverIds.Count == 0)
            {
                Json(new { Result = "error", msg = "上传失败" });
            }
            try
            {
                for (int i = 0; i < serverIds.Count; i++)
                {
                    //获得保存路径
                    string filename = Guid.NewGuid().ToString("N");
                    var url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + acctoken + "&media_id=" + serverIds[i];
                    if (DownLoad(url, Server.MapPath("~/upload/" + urlWhere + "/"), filename + filetype))
                    {
                        imgUrls.Add(host + "/upload/" + urlWhere + "/" + filename + filetype);
                    }
                }
                if (imgUrls.Count == 0)
                {
                    return Json(new { Result = "error", msg = "上传失败" });

                }
                return Json(new { Result = "success", imgs = imgUrls });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "error", msg = ex.Message });
            }
        }
        /// <summary>
        /// 下载文件到指定地址
        /// </summary>
        /// <param name="httpUrl">网络地址</param>
        /// <param name="filePath">保存本地目录</param>
        /// <param name="fileName">保存文件名</param>
        public bool DownLoad(string httpUrl, string filePath, string fileName)
        {
            try
            {
                if (string.IsNullOrEmpty(httpUrl)) return false;

                if (!System.IO.Directory.Exists(filePath))
                {
                    System.IO.Directory.CreateDirectory(filePath);
                }
                using (System.Net.WebClient client = new System.Net.WebClient())
                {
                    var i = 0;
                    DownLoadFile:
                    if (i < 10)
                    {
                        client.DownloadFile(httpUrl, filePath + fileName);
                        if (System.IO.File.Exists(filePath + fileName))
                        {
                            if (new FileInfo(filePath + fileName).Length <= 1024)
                            {
                                System.IO.File.Delete(filePath + fileName);
                                i++;
                                goto DownLoadFile;
                            }
                            return true;
                        }
                        else
                        {
                            i++;
                            goto DownLoadFile;
                        }
                    }
                    return false;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        #region Post/Get提交调用抓取
        /// <summary>
        /// Post/get 提交调用抓取
        /// </summary>
        /// <param name="url">提交地址</param>
        /// <param name="param">参数</param>
        /// <returns>string</returns>
        public static string WebRequestPostOrGet(string sUrl, string sParam)
        {
            byte[] bt = System.Text.Encoding.UTF8.GetBytes(sParam);


            Uri uriurl = new Uri(sUrl);
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uriurl);//HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url + (url.IndexOf("?") > -1 ? "" : "?") + param);
            req.Method = "Post";
            req.Timeout = 120 * 1000;
            req.ContentType = "application/x-www-form-urlencoded;";
            req.ContentLength = bt.Length;


            using (Stream reqStream = req.GetRequestStream())//using 使用可以释放using段内的内存
            {
                reqStream.Write(bt, 0, bt.Length);
                reqStream.Flush();
            }
            try
            {
                using (WebResponse res = req.GetResponse())
                {
                    //在这里对接收到的页面内容进行处理 


                    Stream resStream = res.GetResponseStream();


                    StreamReader resStreamReader = new StreamReader(resStream, System.Text.Encoding.UTF8);


                    string resLine;


                    System.Text.StringBuilder resStringBuilder = new System.Text.StringBuilder();


                    while ((resLine = resStreamReader.ReadLine()) != null)
                    {
                        resStringBuilder.Append(resLine + System.Environment.NewLine);
                    }


                    resStream.Close();
                    resStreamReader.Close();


                    return resStringBuilder.ToString();
                }
            }
            catch (Exception ex)
            {
                return ex.Message;//url错误时候回报错
            }
        }
        #endregion
    }
}
